<template>
	<div class="pageBox">
		<div class="formBox borderClass totalAgent">
			<header class="addAgentFormTop">
				<div class="textB">
					{{ $t('agent.add_total_agent_profile') }}
				</div>
				<div>
					<span class="textColor">*</span>
					{{ $t('common.add_dialog_tips') }}
				</div>
			</header>
			<div class="form-content">
				<el-form
					ref="validateForm"
					:model="formData"
					:rules="rules"
					label-width="230px"
					class="demo-formData"
				>
					<el-form-item
						:label="$t('agent.agent_account') + ':'"
						prop="userName"
					>
							<el-input
								v-model="formData.userName"
								:placeholder="$t('agent.rule_other_tip7')"
							></el-input>
					</el-form-item>
					<el-form-item
						:label="$t('agent.login_password') + ':'"
						prop="password"
					>
						<el-input
							v-model="formData.password"
							:maxlength="12"
							:placeholder="$t('agent.login_password_rules')"
						></el-input>
					</el-form-item>
					 <!-- 安全校验 -->
					 <GoogleKeySelect prop="checkType" v-model="formData.checkType" />
					<el-form-item
						:label="`${$t('agent.top_proxy_belong')}:`"
						prop="proxyAffiliation"
					>
						<el-input
							v-model="formData.proxyAffiliation"
							:placeholder="$t('common.please_enter')"
							v-input="{name: 'onlyInputNumZh'}"
							:maxlength="11"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="$t('agent.agent_type') + ':'"
						prop="accountType"
					>
						<el-select
							v-model="formData.accountType"
							:placeholder="
								$t('agent.rule_select_tip_agent_type')
							"
						>
							<el-option
								v-for="item in accountTypeArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item
						class="current_spetify_item required"
						:label="$t('common.business_model') + ':'"
						:placeholder="$t('common.business_choose_default')"
					>
						<business-model-selector
							v-model="formData.businessModel"
						/>
					</el-form-item>
					<el-form-item
						v-if="formData.businessModel === '1'"
						class="current_spetify_item required"
						label="代理分润模式:"
					>
						<el-select
							v-model="formData.commissionModel"
							:placeholder="
								$t('common.business_choose_default')
							"
						>
							<el-option :value="1" label="占成模式" />
							<el-option :value="2" label="佣金模式" />
						</el-select>
					</el-form-item>

					<AgenGroupSelect v-model="formData.groupId" />

					<el-form-item
						class="current_spetify_item required"
						label="取款限制类型:"
					>
						<el-select
							v-model="formData.withdrawLimitType"
							:placeholder="
								$t('common.business_choose_default')
							"
							disabled
						>
							<el-option value="2" label="流水限制" />
							<el-option value="1" label="账单限制" />
						</el-select>
						<!-- <template>
							<p
								v-if="formData.withdrawLimitType === '1'"
								style="color: #777; line-height: 1;padding-top: 5px;"
							>
								取款时受到“所需有效流水”限制。
							</p>
							<p
								v-else
								style="color: #777; line-height: 1; padding-top: 5px;"
							>
								取款时受到最新账单的“可提现金额”限制。
							</p>
						</template> -->
					</el-form-item>
					<el-form-item
						:label="$t('agent.agent_level_limit') + ':'"
						prop="maxLevels"
					>
						<el-select
							v-model="formData.maxLevels"
							:placeholder="
								$t('agent.rule_select_tip_level_limit')
							"
						>
							<el-option
								v-for="item in agentLevel"
								:key="item.id"
								:label="item.id"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item
						:label="$t('common.choose_merchant') + ':'"
						prop="merchantId"
					>
						<merchant-select
							v-model="formData.merchantId"
							:placeholder="$t('common.please_choose')"
						></merchant-select>
					</el-form-item>
					<AgentRebates
						ref="AgentRebates"
						:isEdit="true"
						:commissionModel="formData.commissionModel"
					/>
					<el-form-item label="备注" prop="applyInfo">
						<el-input
							v-model.trim="formData.applyInfo"
							:rows="4"
							show-word-limit
							type="textarea"
							minlength="4"
							maxlength="500"
						/>
					</el-form-item>
					<el-form-item>
						<el-button
							type="primary"
							:disabled="loading"
							@click="submitForm"
						>
							{{ $t('common.submit') }}
						</el-button>
						<el-button @click="resetForm('validateForm')">
							{{ $t('common.reset') }}
						</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
	</div>
</template>

<script>
import { rules, accountTypeArr } from './rules.js'
import list from '@/mixins/list'
import md5 from 'js-md5'
import BusinessModelSelector from '@/components/Form/BusinessModelSelector.vue'
import AgentRebates from '@/components/AgentRebates'
import AgenGroupSelect from '@/components/AgenGroupSelect'
import GoogleKeySelect from '@/components/GoogleKeySelect'

export default {
  name: 'TotalAgent',
  components: {
    AgentRebates,
    BusinessModelSelector,
	AgenGroupSelect,
	GoogleKeySelect
  },
  mixins: [list],
  props: {
    agentLevel: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      formData: {
		groupId: undefined,
        userName: undefined,
        password: undefined,
		proxyAffiliation: undefined,
        maxLevels: undefined,
        accountType: undefined,
        withdrawLimitType: '1',
        businessModel: '2',
        commissionModel: 1,
		checkType: 1
      }
    }
  },
  computed: {
    appIdArr() {
      return this.globalDics.appId || []
    },
    rules() {
      return rules()
    },
    accountTypeArr
  },
  watch: {
    'formData.businessModel': {
      handler(val) {
        if (val && val === '1') {
          this.formData.withdrawLimitType = '2'
        } else if (val && val === '2') {
          this.formData.withdrawLimitType = '1'
        }

        if (val === '1') {
          this.formData.commissionModel = 2
        } else {
          this.formData.commissionModel = 1
        }
      }
    },
    // 处理页面缓存问题
    $route: {
      handler(route) {
        this.resetForm()
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    formatParams() {
      const params = {
        ...this.formData,
        rebateAllotMode: 1,
        ...(
          this.formData.commissionModel === 1
            ? {
              rebateRateList: this.$refs['AgentRebates'].getValues()
            }
            : {
              commissionRateList: this.$refs['AgentRebates'].getValues(['commissionDzRebates']),
              rebateRateList: this.$refs['AgentRebates'].getValues(['memberPlatform'])
            }
        )

      }
      params.password = `${md5(md5(params.password).toUpperCase()).toUpperCase()}`
      return params
    },
    async resetForm() {
      await this.$refs['validateForm'].resetFields()
      await this.$refs['AgentRebates'].resetFields()

      this.$refs['AgentRebates'].clearValidate('rebateRateTemplateId')
    },
    async validate() {
      return Promise.all([
        new Promise((resolve, reject) => {
          this.$refs['AgentRebates'].validate((err) => {
            if (err) {
              return resolve()
            }

            return reject()
          })
        }),
        new Promise((resolve, reject) => {
          this.$refs['validateForm'].validate((err) => {
            if (err) {
              return resolve()
            }
            return reject()
          })
        })
      ])
    },
    async submitForm() {
      try {
        await this.validate()
        const _rebateRateList = this.$refs['AgentRebates'].getValues()
        _rebateRateList.forEach(e => {
          delete e.platformFlag
          delete e.zhanchengFlag
          delete e.userType
        })
        if (Object.values(_rebateRateList[0]).every((value) => value == 0) &&
          Object.values(_rebateRateList[1]).every((value) => value == 0) &&
          Object.values(_rebateRateList[2]).every((value) => value == 0)) {
          this.$message.error('全部场馆项目不能全为0 至少1个场馆值>0')
          return
        }
        this.loading = true
        const res = await this.$api.addSuperAgentAPI(
          this.formatParams()
        )
        if (res.code === 200) {
          this.$confirm(this.$t('agent.submit_success'), {
            confirmButtonText: this.$t('common.confirm'),
            type: 'success',
            showCancelButton: false
          })
            .then(() => {
              this.resetForm()
            })
            .catch(() => {
              this.resetForm()
            })
          return
        }

        const blackCode = [-10001, -10002, -10003, -10004]
        if (blackCode.includes(res.code)) {
          this.$confirm(
            `${res.msg}，${this.$t('agent.prohibit_add')}！`,
            this.$t('agent.tip'),
            {
              confirmButtonText: this.$t('common.confirm'),
              type: 'warning',
              showCancelButton: false
            }
          )
        } else {
          this.$message({
            message:
              res?.msg || this.$t('agent.interface_exceptions'),
            type: 'error'
          })
        }
      } catch (err) {
        if (err === false) return
        throw err
      } finally {
        this.loading = false
      }
    }
  }
}
</script>
<style  lang="scss">
	.totalAgent .el-form-item__content{

		>.el-input, >.el-select, >.el-textarea{
			width: 360px;
		}
	}
</style>
<style lang="scss" scoped>
.formBox {
	padding-bottom: 30px;
	background: #ffffff;
	border: 1px solid #e4e7ed;
	.demo-formData {
		margin: 30px auto 20px;
		// .el-select {
		// 	width: 100%;
		// }
	}


}

.vi_VN,
.en_US {
	.formBox .demo-formData {
		width: 640px;
	}

	.el-tab-pane {
		overflow: auto;
	}

	.table-wrapper {
		width: 1700px;
	}
}

::v-deep .add-table th.el-table__cell {
	color: #909399;
	font-weight: 700;
	padding: 0;
}
::v-deep .add-table .el-table__row:hover > td.el-table__cell {
	background-color: #fff !important;
}

::v-deep .add-table {
	.el-input-number__decrease {
		display: none;
	}
	.el-input-number__increase {
		display: none;
	}

	.el-input-number .el-input__inner {
		padding: 0;
	}

	.el-input-number {
		width: 80px;
	}
	.el-form-item {
		margin-bottom: 15px;
	}
	.el-form-item__error {
		white-space: nowrap;
	}
}

.form-content {
	align-items: center;
}

::v-deep .current_spetify_item {
	position: relative;
	label.el-form-item__label::before {
		content: '*';
		color: #f56c6c;
		display: inline-box;
		font-size: 14px;
		font-weight: 700;
		margin-right: 5px;
	}
}
</style>
